package com.wusuowei.oauthserver.auth.common;


import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description 用户身份验证转换器
 * @author LGY
 * @date 2023/03/31 00:24
 * @version 1.0.0
 */
@Configuration
public class UserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    private Collection<? extends GrantedAuthority> defaultAuthorities;


    private static final String USER_INFO = "user_name";


    /**
     * 选择存入认证信息中的数据
     *
     * @param map
     * @return
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        Authentication authentication = null;
        if (map.containsKey(USER_INFO)) {
            // 将用户对象作为用户信息。
            Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);
            User user = new User((String) map.get(USER_INFO), (String) null, (List<GrantedAuthority>) authorities);
          //  Object principal = user;
            authentication = new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
        }
        return authentication;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return this.defaultAuthorities;
        } else {
            Object authorities = map.get(AUTHORITIES);
            if (authorities instanceof String) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList((String)authorities);
            } else if (authorities instanceof Collection) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection)authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }
        }
    }
}